import 'dart:async';
import 'dart:convert';
import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:base_lib/dictionary/dictionary_provider.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/dictionary/entity/medical_single_dose_entity.dart'
    as SingleDoseBean;
import 'package:base_lib/dictionary/entity/medical_treat_frequency_entity.dart'
    as TreatBean;
import 'package:base_lib/dictionary/entity/medical_treat_route_entity.dart'
    as TreatRouteBean;
import 'package:common_lib/patient_management/add_patient/add_patient_page.dart';
import 'package:doctor_prescribe_lib/western_medicine/edit_medical/entity/medicine_info_entity.dart';
import 'package:doctor_prescribe_lib/western_medicine/prescription_page/bloc.dart';
import 'package:doctor_prescribe_lib/repository/http.dart';
import 'package:flutter/src/widgets/framework.dart';
import './entity/medicine_info_entity.dart' as MedicineInfoBean;
import '../medical_search/entity/medical_search_entity.dart'
    as MedicalSearchBean;

class EditMedicalBloc extends BaseBloc {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    infoStream?.close();
    singleUnitStream?.close();
    treatStream?.close();
    treatRouteStream?.close();
    useDayStream?.close();
    medicineAmountStream?.close();
    remarkStream?.close();
  }

  int cacheIndex = -1;

  bool isEdit;

  MedicalSearchBean.Datas info;
  StreamController<MedicalSearchBean.Datas> infoStream =
      StreamController.broadcast();

  //单次药量
  int singleDose;

  //单位
  SingleDoseBean.Data singleUnit;
  StreamController<SingleDoseBean.Data> singleUnitStream =
      StreamController.broadcast();

  //给药频率
  TreatBean.Data treat;
  StreamController<TreatBean.Data> treatStream = StreamController.broadcast();

  //给药途径
  TreatRouteBean.Data treatRoute;
  StreamController<TreatRouteBean.Data> treatRouteStream =
      StreamController.broadcast();

  //用药天数
  int useDay;
  StreamController<int> useDayStream = StreamController.broadcast();

  //开药量
  int medicineAmount;
  StreamController<int> medicineAmountStream = StreamController.broadcast();

  //备注
  String remark = '';
  StreamController<String> remarkStream = StreamController.broadcast();

  getMedicineInfo(context, MedicalSearchBean.Datas data, bool isEdit) async {
    this.info = data;
    this.isEdit = isEdit;

    if (PrescriptionPageBloc.rxMedicineList.isNotEmpty) {
      cacheIndex = PrescriptionPageBloc.rxMedicineList
          .indexWhere((element) => element.medicineID == data.medicineID);
      if (cacheIndex != -1) {
        this.isEdit = true;
        info = PrescriptionPageBloc.rxMedicineList[cacheIndex];

        Future.delayed(Duration(milliseconds: 100), () {
          infoStream.add(info);
        });

        Future.delayed(Duration(milliseconds: 200), () {
          setSingleDose(info.takeDose.toString());
          setSingleUnit(info.singleUnit);
          setTreatFrequency(info.treat);
          setTreatRoute(info.treatRoute);
          setUseDay(info.medicationDays.toString());
          setMedicalNum(info.medicineAmount.toString());
          setRemark(info.memo);
        });

        return;
      }
    }

    var result = await PrescribeHttp.getMedicineInfo(data.medicineID);
    if (result.isSuccess) {
      info
        ..medicineName = result.data.medicineName
        ..productSpec = result.data.productSpec
        ..productUnit = result.data.productUnit
        ..formType = result.data.formType
        ..dosage = result.data.dosage;

      infoStream.add(info);

      //设置默认值
      if (info.formType.isNotEmpty) {
        Future.delayed(Duration(milliseconds: 200), () {
          setSingleUnit(SingleDoseBean.Data(dictName: info.formType));
        });
      }
      //设置默认值
      if (info.dosage.isNotEmpty) {
        Future.delayed(Duration(milliseconds: 200), () {
          setTreatRoute(TreatRouteBean.Data(dictName: info.dosage));
        });
      }
    } else {
      ToastUtil.error(result.error.msg);
    }
  }

  void setSingleDose(String str) {
    try {
      singleDose = int.parse(str);
    } catch (e) {
      print(e);
      ToastUtil.error('请输入数字');
    }
  }

  void showSingleUnitPicker(BuildContext context) async {
    var result = await DictionaryProvider.getSingleDose();
    if (result.isSuccess) {
      var list =
          SingleDoseBean.MedicalSingleDoseEntity.fromJson(result.data).data;

      WPicker.showWPicker<SingleDoseBean.Data>(
          context: context,
          selectedItem: singleUnit,
          itemList: list,
          map2string: (e) {
            return e.dictName;
          }).then((value) {
        if (value is SingleDoseBean.Data) {
          setSingleUnit(value);
        }
      });
    } else {
      ToastUtil.error(result.error.msg);
    }
  }

  void setSingleUnit(SingleDoseBean.Data unit) {
    singleUnit = unit;
    singleUnitStream.add(singleUnit);
  }

  void setTreatFrequency(TreatBean.Data value) {
    treat = value;
    treatStream.add(treat);
  }

  void showTreatFrequencyPicker(BuildContext context) async {
    var result = await DictionaryProvider.getTreatFrequency();
    if (result.isSuccess) {
      var list =
          TreatBean.MedicalTreatFrequencyEntity.fromJson(result.data).data;

      WPicker.showWPicker<TreatBean.Data>(
          context: context,
          selectedItem: treat,
          itemList: list,
          map2string: (e) => e.dictName).then((value) {
        if (value is TreatBean.Data) {
          setTreatFrequency(value);
        }
      });
    } else {
      ToastUtil.error(result.error.msg);
    }
  }

  void setTreatRoute(TreatRouteBean.Data value) {
    treatRoute = value;
    treatRouteStream.add(treatRoute);
  }

  void showTreatRoutePicker(BuildContext context) async {
    var result = await DictionaryProvider.getMedicalTreatRoute();
    if (result.isSuccess) {
      var list =
          TreatRouteBean.MedicalTreatRouteEntity.fromJson(result.data).data;

      WPicker.showWPicker<TreatRouteBean.Data>(
          context: context,
          selectedItem: treatRoute,
          itemList: list,
          map2string: (e) => e.dictName).then((value) {
        if (value is TreatRouteBean.Data) {
          setTreatRoute(value);
        }
      });
    } else {
      ToastUtil.error(result.error.msg);
    }
  }

  void setUseDay(String str) {
    try {
      useDay = int.parse(str);
      useDayStream.add(useDay);
    } catch (e) {
      print(e);
      ToastUtil.error('请输入数字');
    }
  }

  void setMedicalNum(String str) {
    try {
      medicineAmount = int.parse(str);
      medicineAmountStream.add(medicineAmount);
    } catch (e) {
      print(e);
      ToastUtil.error('请输入数字');
    }
  }

  ///设置备注
  void setRemark(String str) {
    remark = str;
    remarkStream.add(remark);
  }

  void doSave(BuildContext context) {
    if (singleDose == null) {
      ToastUtil.warning('请输入单次药量');
      return;
    }

    if (singleUnit == null) {
      ToastUtil.warning('请选择单次药量单位');
      return;
    }

    if (treat == null) {
      ToastUtil.warning('请选择给药频率');
      return;
    }

    if (treatRoute == null) {
      ToastUtil.warning('请选择给药途径');
      return;
    }

    if (useDay == null) {
      ToastUtil.warning('请输入用药天数');
      return;
    }

    if (medicineAmount == null) {
      ToastUtil.warning('请输入开药量');
      return;
    }

    var price = info.unitPrice * medicineAmount;

    info
      //用于缓存
      ..singleUnit = singleUnit
      ..treat = treat
      ..treatRoute = treatRoute
      // end
      ..medicineClassID = 0
      ..medicineClassName = '西药'
      ..takeDose = singleDose
      ..unit = singleUnit.dictName
      ..takeFrequence = treat.dictName
      ..takeDirection = treatRoute.dictName
      ..medicineAmount = medicineAmount
      ..price = price
      ..memo = remark
      ..medicationDays = useDay;

    if (cacheIndex != -1) {
      PrescriptionPageBloc.rxMedicineList.removeAt(cacheIndex);
    }

    PrescriptionPageBloc.rxMedicineList.add(info);

    Routers.pop(context, true);
  }
}
